package com.yhd.gmall.mq.receiver;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.stereotype.Component;




/**
 * @author yhd
 * @createtime 2020/10/2 9:55
 * 消息接收端
 */
@Component
@SpringBootConfiguration
@Slf4j
public class ConfirmReceiver {
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.confirm",autoDelete = "false"),
            exchange = @Exchange(value = "exchange.confirm",autoDelete = "false"),
            key = {"routing.confirm"}
    ))
    public void process(Message message, Channel channel){
        log.info("RabbitListener:"+new String(message.getBody()));
        /**
         * 采用手动应答模式，手动确认更为安全稳定
         * 如果手动确认了，在抛出异常，mq不会通知，如果没有手动确认，抛异常mq会一直通知
         */
        try {
            int i=1/0;
            //false 确认一个消息 true 批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //消息是否再次被拒绝
            log.error("come on!");
            //判断是否已经处理过一次消息
            if (message.getMessageProperties().getRedelivered()){
                log.error("消息已重复处理,拒绝再次接收");
                // 拒绝消息，requeue=false 表示不再重新入队，如果配置了死信队列则进入死信队列
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }else {
                log.info("消息即将再次返回队列处理");
                // 参数二：是否批量， 参数三：为是否重新回到队列，true重新入队
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }
}
